package b2.net
{
	import b2.config.*;
	import b2.player.*;
	import b2.player.dataModel.Mail;
	import b2.scene.*;
	import b2.util.*;
	import b2.util.json.*;
	import b2.widget.*;
	import b2.widget.fort.*;
	
	import flash.errors.*;
	import flash.events.*;
	import flash.external.*;
	import flash.net.*;
	import flash.text.*;
	import flash.utils.*;

	//和后台服务器交互助手 
	public class ServerHelper extends EventDispatcher
	{
		//时限（秒）
		public const processTimeOut:int = 10;
		//唯一对象
		static private var instance:ServerHelper;		
		//正在处理标识符
		public var processingFlag:Boolean;	
		//上次请求的时间(单位:秒) 
		public var lastCallId:int;
		//对话号
		private var sessionId:String;
		//回调函数
		private var callBackFunc:Function;
		//同步时的服务器时间(单位：秒）
		public var serverTime:int;
		//同步时的客户端时间（单位：秒）
		public var clientTime:int;
		//发送请求的时间(单位：毫秒）
		private var postTime:int;
		 
		public function ServerHelper()
		{
			super();
		}
		
		public static function getInstance():ServerHelper
		{
			if (!instance)
				instance = new ServerHelper();
			return instance;
		}
		
		//对中文进行UTF编码转化
		private static function utf8Encode(string:String):String 
		{
			string = string.replace(/\r\n/g,'\n');
			string = string.replace(/\r/g,'\n');
			
			var utfString:String = "";
			
			for (var i:int = 0 ; i < string.length ; i++) 
			{
				var chr:Number = string.charCodeAt(i);
				if (chr < 128) 
				{
					utfString += String.fromCharCode(chr);
				}
				else if ((chr > 127) && (chr < 2048)) 
				{
					utfString += String.fromCharCode((chr >> 6) | 192);
					utfString += String.fromCharCode((chr & 63) | 128);
				}
				else 
				{
					utfString += String.fromCharCode((chr >> 12) | 224);
					utfString += String.fromCharCode(((chr >> 6) & 63) | 128);
					utfString += String.fromCharCode((chr & 63) | 128);
				}
			}
			return utfString;
		}
		
		//生成指纹
		public static function generateSig(variables:URLVariables, secret:String):String
		{
			var varArray:Array = new Array();
			for (var key:String in variables)
			{
				varArray.push(key + "=" + variables[key]);
			} 
			varArray.sort();
			var varStr:String = varArray.join("");
			varStr += secret;
			varStr = utf8Encode(varStr);
			return Md5.hash(varStr);
		}
		
		//当前日期
		public function getClientDate():int
		{
			return Math.floor(this.serverTime / 86400);
		}
		
		//模拟的当前的服务器系统时间(秒)
		public function currentSeconds():int
		{
			return serverTime + getTimer() / 1000 - clientTime; 
		}
		
		private function handleIOError(event:IOErrorEvent):void
		{
			processingFlag = false;
		} 
		
		public function postRequest(webpage:String, variables:URLVariables, handleFunction:Function, callBackFunc:Function = null, force:Boolean = false):Boolean
		{
			var currentSeconds:int = currentSeconds();
			if (!force && processingFlag && currentSeconds - lastCallId < processTimeOut)
				return false;
			if (callBackFunc != null)
				this.callBackFunc = callBackFunc;
			if (PlayerInfoManager.getInstance().myUserId > 0)
			{
				variables.userId = PlayerInfoManager.getInstance().myUserId;
			}
			variables.sessionId = this.sessionId;
			var callId:int = currentSeconds > lastCallId ? currentSeconds : lastCallId + 1;
			variables.callId = callId;
			variables.b2Sig = generateSig(variables, Profile.serverSecret);
			var request:URLRequest = new URLRequest(webpage);
			request.method = URLRequestMethod.POST;
			request.data = variables;
			var loader:URLLoader = new URLLoader();
			loader.dataFormat = URLLoaderDataFormat.BINARY;
			loader.addEventListener(Event.COMPLETE, handleFunction);
			loader.addEventListener(IOErrorEvent.IO_ERROR, handleIOError);
			SceneManager.getInstance().customizeMouse();
			try
			{
				processingFlag = true;
				lastCallId = callId;
				postTime = getTimer();
				loader.load(request);
			}
			catch (error:Error)
			{
				SceneManager.getInstance().restoreSystemMouse();
				processingFlag = false;
				trace("B2: Post request error occurred.");
			}
			return processingFlag;
		}
		
		//预处理
		private function preProcess(dataXML:XML):String
		{
			SceneManager.getInstance().restoreSystemMouse();
			processingFlag = false;
			serverTime = parseInt(dataXML.timeStamp);
			var phpTime:int = parseInt(dataXML.phpElapsedTime);
			var totalTime:int = getTimer() - postTime;
			DebugPane.getInstance().addInfo(dataXML.action + ": total time(" + totalTime + "), php time(" + phpTime + ")");
			clientTime = getTimer() / 1000;
			var result:String = dataXML.result;
			if (result == "other login")
			{
				var messageBox:MessageBox = new MessageBox("用户已经在其他地方登陆！\n请重新登陆！");
				messageBox.setOKCall(redirectToGamePage);
				WidgetManager.getInstance().popOut([messageBox], true, true);
			}
			return result;
		}
		
		//结束处理
		private function postProcess(dataXML:XML):void
		{
			var serverEvent:ServerEvent = new ServerEvent(dataXML.action);
			serverEvent.action = dataXML.action;
			serverEvent.result = dataXML.result;
			dispatchEvent(serverEvent);
		}
		
		//调试登陆
		public function loginMeDebug():Boolean
		{
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.GET_SESSION;
			return postRequest(Profile.URL_Login, variables, handleGetSessionId, null, true);
		}
		
		private function handleGetSessionId(event:Event):void
		{
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			this.sessionId = dataXML.sessionId;
			loginMe();
			postProcess(dataXML);
		}
		
		//获得好友列表
		public function getFriendList(force:Boolean):Boolean
		{
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.GET_FRIEND_LIST;
			variables.openid = PlayerInfoManager.getInstance().openid;
			variables.openkey = PlayerInfoManager.getInstance().openkey;
			variables.pf = PlayerInfoManager.getInstance().pf;
			return postRequest(Profile.URL_Friend, variables, handleGetFriendList, null, force);
		}
		
		private function handleGetFriendList(event:Event):void
		{
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var playerIds:Array = new Array();
			for (var i:int = 0; i < dataXML.playerInfo.length(); i++)
			{
				var playerInfo:PlayerInfo = new PlayerInfo(dataXML.playerInfo[i]);
				//Fix bug: 好友信息覆盖了自己的包裹信息导致战斗时武器消失
				if (playerInfo.id == PlayerInfoManager.getInstance().myUserId)
				{
					var me:PlayerInfo = PlayerInfoManager.getInstance().me;
					me.attackedCount = playerInfo.attackedCount;
				}
				else
				{
					PlayerInfoManager.getInstance().players[playerInfo.id] = playerInfo;
				}
				playerIds.push(playerInfo.id);
			}
			var serverEvent:ServerEvent = new ServerEvent(dataXML.action);
			serverEvent.action = dataXML.action;
			serverEvent.result = dataXML.result;
			serverEvent.userData = playerIds;
			dispatchEvent(serverEvent);
		}
		
		//检查是否有新的社交信息
		public function checkNewSocialInfo(force:Boolean = false):Boolean
		{
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.CHECK_NEW_SOCIAL_INFO;
			return postRequest(Profile.URL_Action, variables, handleCheckNewSocialInfo, null, force);
		}
		
		private function handleCheckNewSocialInfo(event:Event):void
		{
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var serverEvent:ServerEvent = new ServerEvent(dataXML.action);
			serverEvent.action = dataXML.action;
			serverEvent.result = dataXML.result;
			serverEvent.userData = Boolean(parseInt(dataXML.hasNewSocialInfo));
			dispatchEvent(serverEvent);
		}
		
		//获得玩家社交信息
		public function getSocialInfo(allFlag:Boolean, force:Boolean = false):Boolean
		{
			var variables:URLVariables = new URLVariables();
			variables.allFlag = allFlag ? 1 : 0;
			variables.action = ServerEvent.GET_SOCIAL_INFO;
			return postRequest(Profile.URL_Action, variables, handleGetSocialInfo, null, force);
		}
		
		private function handleGetSocialInfo(event:Event):void
		{
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var me:PlayerInfo = PlayerInfoManager.getInstance().me;
			me.socialPackage = new SocialPackage(dataXML.socialPackage[0]);
			postProcess(dataXML);
		}
		
		//获得玩家信息
		public function getPlayerInfo(playerId:int):Boolean
		{
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.GET_PLAYER_INFO;
			variables.playerId = playerId;
			return postRequest(Profile.URL_Action, variables, handleGetPlayerInfo);
		}
		
		private function handleGetPlayerInfo(event:Event):void
		{
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var playerInfo:PlayerInfo = new PlayerInfo(dataXML.playerInfo[0]);
			PlayerInfoManager.getInstance().players[playerInfo.id] = playerInfo;
			playerInfo.objPackage = new ObjPackage(dataXML.objPackage[0]);
			playerInfo.tankPackage = new TankPackage(dataXML.tankPackage[0]);
			playerInfo.tankPackage.sortWithFightPoint();
			postProcess(dataXML);
		}
		
		//Q点直购
		public function buyGoods(payitem:String, goodsmeta:String, goodsurl:String):Boolean
		{
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.BUY_GOODS;
			var playerManager:PlayerInfoManager = PlayerInfoManager.getInstance();
			variables.openid = playerManager.openid;
			variables.openkey = playerManager.openkey;
			variables.pf = playerManager.pf;
			variables.pfkey = playerManager.pfkey;
			variables.payitem = payitem;
			variables.goodsmeta = goodsmeta;
			variables.goodsurl = goodsurl;
			return postRequest(Profile.URL_BuyGoods, variables, handleBuyGoods);
		}
		
		private function handleBuyGoods(event:Event):void
		{
			SceneManager.getInstance().restoreSystemMouse();
			processingFlag = false;
			var jsonObj:Object = JSON.decode(event.target.data);
			if (jsonObj['ret'] == 0)
			{
				ExternalInterface.call("tfBuyItem", jsonObj.url_params);
			}
			else
			{
				DebugPane.getInstance().addInfo("handleBuyGoods Error: " + event.target.data); 
			}
		}
		
		//黄钻每日礼物领取
		public function fetchVipDailyPresent():Boolean
		{
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.FETCH_VIP_DAILY_PRESENT;
			var playerManager:PlayerInfoManager = PlayerInfoManager.getInstance();
			variables.openid = playerManager.openid;
			variables.openkey = playerManager.openkey;
			variables.pf = playerManager.pf;
			variables.pfkey = playerManager.pfkey;
			variables.tokentype = 1;
			variables.discountid = Profile.VIP_DAILY_PRESENT_ACTIVITY_ID;
			return postRequest(Profile.URL_GetToken, variables, handleFetchVipDailyPresent);
		}
		
		private function handleFetchVipDailyPresent(event:Event):void
		{
			SceneManager.getInstance().restoreSystemMouse();
			processingFlag = false;
			var jsonObj:Object = JSON.decode(event.target.data);
			if (jsonObj['ret'] == 0)
			{
				DebugPane.getInstance().addInfo("handleFetchVipDailyPresent: " + event.target.data);
				ExternalInterface.call("tfShowVipGift", Profile.VIP_DAILY_PRESENT_ACTIVITY_ID, jsonObj.token, jsonObj.mid);
			}
			else
			{
				DebugPane.getInstance().addInfo("handleFetchVipDailyPresent Error: " + event.target.data); 
			}
		}
		
		//登陆
		public function loginMe():Boolean
		{
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.LOGIN_ME;
			variables.openid = PlayerInfoManager.getInstance().openid;
			variables.openkey = PlayerInfoManager.getInstance().openkey;
			variables.pf = PlayerInfoManager.getInstance().pf;
			return postRequest(Profile.URL_Login, variables, handleLoginMe);
		}
		
		private function handleLoginMe(event:Event):void
		{
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			this.sessionId = dataXML.sessionId;
			BSound.getInstance().musicVolume = parseInt(dataXML.musicVolume) / 1000;
			BSound.getInstance().effectVolume = parseInt(dataXML.effectVolume) / 1000;
			var me:PlayerInfo = new PlayerInfo(dataXML.playerInfo[0]);
			PlayerInfoManager.getInstance().myUserId = me.id;
			PlayerInfoManager.getInstance().players[me.id] = me;
			me.objPackage = new ObjPackage(dataXML.objPackage[0]);
			me.tankPackage = new TankPackage(dataXML.tankPackage[0]);
			me.taskPackage = new TaskPackage(dataXML.taskPackage[0]);
			me.campPackage = new CampPackage(dataXML.campPackage[0]);
			me.mailPackage = new MailPackage(dataXML.mailPackage[0]);
			me.status = new Status(me.id);
			postProcess(dataXML);
		}
		
		//选择坦克
		public function getMail(userId:int, mailId:int):Boolean
		{
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.GET_MAIL;
			variables.mailId = mailId;
			variables.userId = userId;
			return postRequest(Profile.URL_Action, variables, handleGetMail);
		}
		
		//选择坦克
		private function handleGetMail(event:Event):void
		{
			InProcessWindow.getInstance().hide();
			
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var player:PlayerInfo = PlayerInfoManager.getInstance().players[PlayerInfoManager.getInstance().myUserId];
			if (dataXML.objPackage != undefined)
				player.objPackage = new ObjPackage(dataXML.objPackage[0]);
			if (dataXML.tankPackage != undefined)
				player.tankPackage = new TankPackage(dataXML.tankPackage[0]);
			if (dataXML.mailPackage != undefined)
				player.mailPackage = new MailPackage(dataXML.mailPackage[0]);
			postProcess(dataXML);
		}
		
		//选择坦克
		public function selectTank(tankIndex:int):Boolean
		{
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.SELECT_TANK;
			variables.tankIndex = tankIndex;
			return postRequest(Profile.URL_Action, variables, handleSelectTank);
		}
		
		private function handleSelectTank(event:Event):void
		{
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var me:PlayerInfo = PlayerInfoManager.getInstance().me;
			me.campTankId = dataXML.campTankId;
			postProcess(dataXML);
		}
		
		//结束新手引导
		public function finishGuide():Boolean
		{
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.FINISH_GUIDE;
			return postRequest(Profile.URL_Action, variables, handleFinishGuide, null, true);
		}
		
		private function handleFinishGuide(event:Event):void
		{
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			postProcess(dataXML);
		}
		
		//结束比赛
		public function endMatch(matchIndex:int, matchScore:int, goalFlag:int, objectBalance:String):Boolean
		{
			var me:PlayerInfo = PlayerInfoManager.getInstance().me;
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.END_MATCH;
			variables.matchIndex = matchIndex;
			variables.matchScore = matchScore;
			variables.goalFlag = goalFlag;
			variables.objectBalance = objectBalance;
			return postRequest(Profile.URL_Action, variables, handleEndMatch);
		}
		
		private function handleEndMatch(event:Event):void
		{
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var me:PlayerInfo = PlayerInfoManager.getInstance().me;
			if (dataXML.campPackage != undefined)
				me.campPackage = new CampPackage(dataXML.campPackage[0]);
			if (dataXML.objPackage != undefined)
				me.objPackage = new ObjPackage(dataXML.objPackage[0]);
			var matchIndex:int = parseInt(dataXML.matchIndex);
			var weeklyRanking:int = parseInt(dataXML.ranking[0]);
			var totalRanking:int = parseInt(dataXML.ranking[1]);
			if (weeklyRanking >= 0 || totalRanking >= 0)
			{
				var matchWinBox:MatchWinBox = new MatchWinBox(matchIndex, weeklyRanking, totalRanking);
				WidgetManager.getInstance().popOut([matchWinBox], true, true);
			}
			postProcess(dataXML);
		}
		
		//结束好友战斗
		public function endFriendFight(targetId:int, honourChange:int, goalFlag:int, objectBalance:String):Boolean
		{
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.END_FRIEND_FIGHT;
			variables.targetId = targetId;
			variables.honourChange = honourChange;
			variables.goalFlag = goalFlag;
			variables.objectBalance = objectBalance;
			return postRequest(Profile.URL_Action, variables, handleEndFriendFight);
		}
		
		private function handleEndFriendFight(event:Event):void
		{
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var me:PlayerInfo = PlayerInfoManager.getInstance().me;
			if (dataXML.objPackage != undefined)
				me.objPackage = new ObjPackage(dataXML.objPackage[0]);
			postProcess(dataXML);
		}
		
		//结束战斗
		public function endFight(campIndex:int, goalFlag:int, objectBalance:String):Boolean
		{
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.END_FIGHT;
			variables.campIndex = campIndex;
			variables.goalFlag = goalFlag;
			variables.objectBalance = objectBalance;
			return postRequest(Profile.URL_Action, variables, handleEndFight);
		}
		
		private function handleEndFight(event:Event):void
		{
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var me:PlayerInfo = PlayerInfoManager.getInstance().players[PlayerInfoManager.getInstance().myUserId];
			if (dataXML.campPackage != undefined)
				me.campPackage = new CampPackage(dataXML.campPackage[0]);
			if (dataXML.objPackage != undefined)
				me.objPackage = new ObjPackage(dataXML.objPackage[0]);
			postProcess(dataXML);
		}
		
		//检查比赛资格
		public function checkMatchQualification(matchIndex:int):Boolean
		{
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.CHECK_MATCH_QUALIFICATION;
			variables.matchIndex = matchIndex;
			return postRequest(Profile.URL_Action, variables, handleCheckMatchQualification);
		}  
		
		private function handleCheckMatchQualification(event:Event):void
		{
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var serverEvent:ServerEvent = new ServerEvent(dataXML.action);
			serverEvent.action = dataXML.action;
			serverEvent.result = dataXML.result;
			serverEvent.userData = [parseInt(dataXML.matchIndex), Boolean(parseInt(dataXML.qualified))];
			dispatchEvent(serverEvent);
		}
		
		//获取比赛信息
		public function getMatchInfo(matchIndex:int):Boolean
		{
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.GET_MATCH_INFO;
			variables.matchIndex = matchIndex;
			return postRequest(Profile.URL_Action, variables, handleGetMatchInfo);
		}
		
		private function handleGetMatchInfo(event:Event):void
		{
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var matchRankingList:Array = new Array();
			if (dataXML != null)
			{
				for (var j:int = 0; j < dataXML.matchInfo.length(); j++)
				{
					var rankings:Array = new Array();
					for (var i:int = 0; i < dataXML.matchInfo[j].matchRanking.length(); i++)
					{
						var ranking:MatchRankingInfo = new MatchRankingInfo(dataXML.matchInfo[j].matchRanking[i]);
						rankings.push(ranking);
					}
					matchRankingList.push(rankings);
				}
			}
			var serverEvent:ServerEvent = new ServerEvent(dataXML.action);
			serverEvent.action = dataXML.action;
			serverEvent.result = dataXML.result;
			serverEvent.userData = matchRankingList;
			dispatchEvent(serverEvent);
		}
		
		//获取排名信息
		public function getRankingInfo():Boolean
		{
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.GET_RANKING;
			return postRequest(Profile.URL_Action, variables, handleGetRankingInfo);
		}
		
		private function handleGetRankingInfo(event:Event):void
		{
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var serverEvent:ServerEvent = new ServerEvent(dataXML.action);
			serverEvent.action = dataXML.action;
			serverEvent.result = dataXML.result;
			serverEvent.userData = new RankingPackage(dataXML);
			dispatchEvent(serverEvent);
		}
		
		//获取任务信息
		public function getTask():Boolean
		{
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.GET_TASK;
			return postRequest(Profile.URL_Action, variables, handleGetTask);
		}
		
		private function handleGetTask(event:Event):void
		{
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var me:PlayerInfo = PlayerInfoManager.getInstance().players[PlayerInfoManager.getInstance().myUserId];
			if (dataXML.taskPackage != undefined)
				me.taskPackage = new TaskPackage(dataXML.taskPackage[0]);
			if (dataXML.campPackage != undefined)
				me.campPackage = new CampPackage(dataXML.campPackage[0]);
			postProcess(dataXML);
		}
		
		//接受任务
		public function acceptTask(taskIndex:int, campIndex:int):Boolean
		{
			InProcessWindow.getInstance().show("正在接受任务");
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.ACCEPT_TASK;
			variables.taskIndex = taskIndex;
			variables.campIndex = campIndex;
			return postRequest(Profile.URL_Action, variables, handleAcceptTask, null, true);
		}
		
		private function handleAcceptTask(event:Event):void
		{
			InProcessWindow.getInstance().hide();
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var me:PlayerInfo = PlayerInfoManager.getInstance().players[PlayerInfoManager.getInstance().myUserId];
			if (dataXML.taskPackage != undefined)
				me.taskPackage = new TaskPackage(dataXML.taskPackage[0]);
			postProcess(dataXML);
		}
		
		//完成任务
		public function accomplishTask(taskIndex:int, objectBalance:String):Boolean
		{
			InProcessWindow.getInstance().show("正在提交任务");
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.ACCOMP_TASK;
			variables.taskIndex = taskIndex;
			variables.objectBalance = objectBalance;
			return postRequest(Profile.URL_Action, variables, handleAccomplishTask, null, true);
		}
		
		private function handleAccomplishTask(event:Event):void
		{
			InProcessWindow.getInstance().hide();
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var me:PlayerInfo = PlayerInfoManager.getInstance().players[PlayerInfoManager.getInstance().myUserId];
			if (dataXML.taskPackage != undefined)
				me.taskPackage = new TaskPackage(dataXML.taskPackage[0]);
			if (dataXML.objPackage != undefined)
				me.objPackage = new ObjPackage(dataXML.objPackage[0]);
			postProcess(dataXML);
		}
		
		//获取包裹和坦克信息
		public function getPackageAndTank():Boolean
		{
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.GET_PACKAGE_AND_TANK;
			return postRequest(Profile.URL_Action, variables, handleGetPackageAndTank);
		}
		
		private function handleGetPackageAndTank(event:Event):void
		{
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var player:PlayerInfo = PlayerInfoManager.getInstance().players[PlayerInfoManager.getInstance().myUserId];
			if (dataXML.objPackage != undefined)
				player.objPackage = new ObjPackage(dataXML.objPackage[0]);
			if (dataXML.tankPackage != undefined)
				player.tankPackage = new TankPackage(dataXML.tankPackage[0]);
			if (dataXML.mailPackage != undefined)
				player.mailPackage = new MailPackage(dataXML.mailPackage[0]);
			postProcess(dataXML);
		}
		
		//更换出战坦克
		public function changeCampTank(tankId:int):Boolean
		{
			InProcessWindow.getInstance().show("正在更换出战坦克");
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.CHANGE_CAMP_TANK;
			variables.tankId = tankId;
			return postRequest(Profile.URL_Action, variables, handleChangeCampTank);
		}

		private function handleChangeCampTank(event:Event):void
		{
			InProcessWindow.getInstance().hide();
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var me:PlayerInfo = PlayerInfoManager.getInstance().me;
			me.campTankId = dataXML.campTankId;
			postProcess(dataXML);
		}
		
		//更换装备
		public function changeEquip(newEquipComIndex:String, originalEquipComIndex:String, callBackFunc:Function = null):Boolean
		{
			InProcessWindow.getInstance().show("正在装备");
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.CHANGE_EQUIP;
			if (newEquipComIndex != null)
			{
				var newEquipComIndexArr:Array = newEquipComIndex.split("_");
				variables.newEquipIndex = parseInt(newEquipComIndexArr[0]);
				variables.newEquipBasicLevel = parseInt(newEquipComIndexArr[1]);
				variables.newEquipStrengthenLevel = parseInt(newEquipComIndexArr[2]);
				variables.newEquipTankId = parseInt(newEquipComIndexArr[3]);
			}
			if (originalEquipComIndex != null)
			{
				var originalEquipComIndexArr:Array = originalEquipComIndex.split("_");
				variables.originalEquipIndex = parseInt(originalEquipComIndexArr[0]);
				variables.originalEquipBasicLevel = parseInt(originalEquipComIndexArr[1]);
				variables.originalEquipStrengthenLevel = parseInt(originalEquipComIndexArr[2]);
				variables.originalEquipTankId = parseInt(originalEquipComIndexArr[3]);
			}
			return postRequest(Profile.URL_Action, variables, handleChangeEquip, callBackFunc);
		}
		
		private function handleChangeEquip(event:Event):void
		{
			InProcessWindow.getInstance().hide();
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var player:PlayerInfo = PlayerInfoManager.getInstance().players[PlayerInfoManager.getInstance().myUserId];
			if (dataXML.objPackage != undefined)
				player.objPackage = new ObjPackage(dataXML.objPackage[0]);
			if (dataXML.tankPackage != undefined)
				player.tankPackage = new TankPackage(dataXML.tankPackage[0]);
			postProcess(dataXML);
		}
		
		//更新战力
		public function syncFightPoint(fightPoint:int):Boolean
		{
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.SYNC_FIGHT_POINT;
			variables.fightPoint = fightPoint;
			return postRequest(Profile.URL_Action, variables, handleSyncFightPoint);
		}
		
		private function handleSyncFightPoint(event:Event):void
		{
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			postProcess(dataXML);
		}
		
		//购买物品
		public function purchaseObject(objectIndex:int, objectNum:int, priceOil:int, priceGas:int, priceHonour:int):Boolean
		{
			InProcessWindow.getInstance().show("正在提交购买");
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.PURCHASE;
			variables.objectIndex = objectIndex;
			variables.objectNum = objectNum;
			variables.priceOil = priceOil;
			variables.priceGas = priceGas;
			variables.priceHonour = priceHonour;
			return postRequest(Profile.URL_Action, variables, handlePurchaseObject);
		}

		private function handlePurchaseObject(event:Event):void
		{
			InProcessWindow.getInstance().hide();
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var player:PlayerInfo = PlayerInfoManager.getInstance().players[PlayerInfoManager.getInstance().myUserId];
			if (dataXML.objPackage != undefined)
				player.objPackage = new ObjPackage(dataXML.objPackage[0]);
			if (dataXML.tankPackage != undefined)
				player.tankPackage = new TankPackage(dataXML.tankPackage[0]);
			postProcess(dataXML);
		}
		
		//出售物品
		public function sellObject(tankId:int, objectIndex:int, basicLevel:int, strengthenLevel:int, objectNum:int, priceOil:int):Boolean
		{
			InProcessWindow.getInstance().show("正在提交卖出");
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.SELL;
			variables.tankId = tankId;
			variables.objectIndex = objectIndex;
			variables.basicLevel = basicLevel;
			variables.strengthenLevel = strengthenLevel;
			variables.objectNum = objectNum;
			variables.priceOil = priceOil;
			return postRequest(Profile.URL_Action, variables, handleSellObject);
		}

		private function handleSellObject(event:Event):void
		{
			InProcessWindow.getInstance().hide();
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var player:PlayerInfo = PlayerInfoManager.getInstance().players[PlayerInfoManager.getInstance().myUserId];
			if (dataXML.objPackage != undefined)
				player.objPackage = new ObjPackage(dataXML.objPackage[0]);
			if (dataXML.tankPackage != undefined)
				player.tankPackage = new TankPackage(dataXML.tankPackage[0]);
			postProcess(dataXML);
		}
		
		//消耗
		public function expendVert(tankId:int, objectIndex:int, objectNum:int, basicLevel:int = 0, strengthenLevel:int = 0):Boolean
		{
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.SELL;
			variables.tankId = tankId;
			variables.objectIndex = objectIndex;
			variables.basicLevel = basicLevel;
			variables.strengthenLevel = strengthenLevel;
			variables.objectNum = objectNum;
			variables.priceOil = 0;
			return postRequest(Profile.URL_Action, variables, handleExpendVert);
		}

		private function handleExpendVert(event:Event):void
		{
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var player:PlayerInfo = PlayerInfoManager.getInstance().players[PlayerInfoManager.getInstance().myUserId];
			if (dataXML.objPackage != undefined)
				player.objPackage = new ObjPackage(dataXML.objPackage[0]);
			if (dataXML.tankPackage != undefined)
				player.tankPackage = new TankPackage(dataXML.tankPackage[0]);
			postProcess(dataXML);
		}

		//强化物品
		public function strengthenObj(objectIndex:int, objectBasicLevel:int, objectStrengthenLevel:int, tankId:int, 
			objectBalance:String, successFlag:Boolean):Boolean
		{
			InProcessWindow.getInstance().show("正在强化物品");
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.STRENGTHEN;
			variables.objectIndex = objectIndex;
			variables.basicLevel = objectBasicLevel;
			variables.strengthenLevel = objectStrengthenLevel;
			variables.tankId = tankId;
			variables.objectBalance = objectBalance;
			variables.successFlag = int(successFlag);
			return postRequest(Profile.URL_Action, variables, handleStrengthenObj);
		} 
		
		private function handleStrengthenObj(event:Event):void
		{
			InProcessWindow.getInstance().hide();
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var player:PlayerInfo = PlayerInfoManager.getInstance().players[PlayerInfoManager.getInstance().myUserId];
			if (dataXML.objPackage != undefined)
				player.objPackage = new ObjPackage(dataXML.objPackage[0]);
			postProcess(dataXML);
		}
		
		//强化坦克
		public function strengthenTank(tankId:int, objectIndex:int, objectBasicLevel:int, objectStrengthenLevel:int, 
			objectBalance:String, successFlag:Boolean):Boolean
		{
			InProcessWindow.getInstance().show("正在强化坦克");
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.STRENGTHEN_TANK;
			variables.objectIndex = objectIndex;
			variables.basicLevel = objectBasicLevel;
			variables.strengthenLevel = objectStrengthenLevel;
			variables.tankId = tankId;
			variables.objectBalance = objectBalance;
			variables.successFlag = successFlag;
			return postRequest(Profile.URL_Action, variables, handleStrengthenTank);
		}
		
		private function handleStrengthenTank(event:Event):void
		{
			InProcessWindow.getInstance().hide();
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var player:PlayerInfo = PlayerInfoManager.getInstance().players[PlayerInfoManager.getInstance().myUserId];
			if (dataXML.tankPackage != undefined)
				player.tankPackage = new TankPackage(dataXML.tankPackage[0]);
			if (dataXML.objPackage != undefined)
				player.objPackage = new ObjPackage(dataXML.objPackage[0]);
			postProcess(dataXML);
		}
		
		//合成物品
		public function fuseObj(objectIndex:int, objectBasicLevel:int, objectStrengthenLevel:int, tankId:int, 
			objectBalance:String, successFlag:Boolean):Boolean
		{
			InProcessWindow.getInstance().show("正在合成物品");
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.FUSE_OBJ;
			variables.objectIndex = objectIndex;
			variables.basicLevel = objectBasicLevel;
			variables.strengthenLevel = objectStrengthenLevel;
			variables.tankId = tankId;
			variables.objectBalance = objectBalance;
			variables.successFlag = successFlag;
			return postRequest(Profile.URL_Action, variables, handleFuseObj);
		}
		
		private function handleFuseObj(event:Event):void
		{
			InProcessWindow.getInstance().hide();
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var player:PlayerInfo = PlayerInfoManager.getInstance().players[PlayerInfoManager.getInstance().myUserId];
			if (dataXML.objPackage != undefined)
				player.objPackage = new ObjPackage(dataXML.objPackage[0]);
			var serverEvent:ServerEvent = new ServerEvent(dataXML.action);
			serverEvent.action = dataXML.action;
			serverEvent.result = dataXML.result;
			serverEvent.userData = new Object();
			serverEvent.userData.objIndex = parseInt(dataXML.objIndex);
			serverEvent.userData.basicLevel = parseInt(dataXML.basicLevel);
			serverEvent.userData.strengthenLevel = parseInt(dataXML.strengthenLevel);
			dispatchEvent(serverEvent);
		}
		
		//合成坦克
		public function fuseTank(tankId1:int, tankId2:int, objectIndex:int, objectBasicLevel:int, objectStrengthenLevel:int, 
			objectBalance:String, successFlag:Boolean):Boolean
		{
			InProcessWindow.getInstance().show("正在合成坦克");
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.FUSE_TANK;
			variables.objectIndex = objectIndex;
			variables.basicLevel = objectBasicLevel;
			variables.strengthenLevel = objectStrengthenLevel;
			variables.tankId1 = tankId1;
			variables.tankId2 = tankId2;
			variables.objectBalance = objectBalance;
			variables.successFlag = successFlag;
			return postRequest(Profile.URL_Action, variables, handleFuseTank);
		}
		
		private function handleFuseTank(event:Event):void
		{
			InProcessWindow.getInstance().hide();
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var player:PlayerInfo = PlayerInfoManager.getInstance().players[PlayerInfoManager.getInstance().myUserId];
			if (dataXML.objPackage != undefined)
				player.objPackage = new ObjPackage(dataXML.objPackage[0]);
			if (dataXML.tankPackage != undefined)
				player.tankPackage = new TankPackage(dataXML.tankPackage[0]);
			var serverEvent:ServerEvent = new ServerEvent(dataXML.action);
			serverEvent.action = dataXML.action;
			serverEvent.result = dataXML.result;
			serverEvent.userData = new Object();
			serverEvent.userData.objIndex = parseInt(dataXML.objIndex);
			serverEvent.userData.basicLevel = parseInt(dataXML.basicLevel);
			serverEvent.userData.strengthenLevel = parseInt(dataXML.strengthenLevel);
			dispatchEvent(serverEvent);
		}

		//熔炼坦克
		public function mixtureTank(tankId1:int, tankId2:int, objectIndex:int, objectBasicLevel:int, objectStrengthenLevel:int, 
			objectBalance:String, successFlag:Boolean):Boolean
		{
			InProcessWindow.getInstance().show("正在熔炼坦克");
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.MIXTURE_TANK;
			variables.objectIndex = objectIndex;
			variables.basicLevel = objectBasicLevel;
			variables.strengthenLevel = objectStrengthenLevel;
			variables.tankId1 = tankId1;
			variables.tankId2 = tankId2;
			variables.objectBalance = objectBalance;
			variables.successFlag = successFlag;
			return postRequest(Profile.URL_Action, variables, handleMixtureTank);
		}
		
		private function handleMixtureTank(event:Event):void
		{
			InProcessWindow.getInstance().hide();
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var player:PlayerInfo = PlayerInfoManager.getInstance().players[PlayerInfoManager.getInstance().myUserId];
			if (dataXML.objPackage != undefined)
				player.objPackage = new ObjPackage(dataXML.objPackage[0]);
			if (dataXML.tankPackage != undefined)
				player.tankPackage = new TankPackage(dataXML.tankPackage[0]);
			var serverEvent:ServerEvent = new ServerEvent(dataXML.action);
			serverEvent.action = dataXML.action;
			serverEvent.result = dataXML.result;
			serverEvent.userData = new Object();
			serverEvent.userData.objIndex = parseInt(dataXML.objIndex);
			serverEvent.userData.basicLevel = parseInt(dataXML.basicLevel);
			serverEvent.userData.strengthenLevel = parseInt(dataXML.strengthenLevel);
			dispatchEvent(serverEvent);
		}
		
		public function postMail(mail:Mail, objectBalance:String):Boolean
		{
			InProcessWindow.getInstance().show("正在发送邮件");
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.POST_EMAIL;
			var dataString:String = JSON.encode(mail);
			dataString = utf8Encode(dataString);
			variables.mail = escape(dataString);
			variables.objectBalance = objectBalance;
			return postRequest(Profile.URL_Action, variables, handlePostMail);
		}
		
		private function handlePostMail(event:Event):void
		{
			InProcessWindow.getInstance().hide();
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var player:PlayerInfo = PlayerInfoManager.getInstance().players[PlayerInfoManager.getInstance().myUserId];
			if (dataXML.tankPackage != undefined)
				player.tankPackage = new TankPackage(dataXML.tankPackage[0]);
			if (dataXML.objPackage != undefined)
				player.objPackage = new ObjPackage(dataXML.objPackage[0]);
			if (dataXML.mailPackage != undefined)
				player.mailPackage = new MailPackage(dataXML.mailPackage[0]);
			postProcess(dataXML);
		}

		//获得新手礼物
		public function fetchNewPlayerGift(objectBalance:String):Boolean
		{
			InProcessWindow.getInstance().show("正在获取新手礼物");
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.FETCH_NEW_PLAYER_GIFT;
			variables.objectBalance = objectBalance;
			return postRequest(Profile.URL_Action, variables, handleFetchNewPlayerGift);
		}
		
		private function handleFetchNewPlayerGift(event:Event):void
		{
			InProcessWindow.getInstance().hide();
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var me:PlayerInfo = PlayerInfoManager.getInstance().me;
			me.fetchNewPlayerGift = true;
			if (dataXML.objPackage != undefined)
				me.objPackage = new ObjPackage(dataXML.objPackage[0]);
			if (dataXML.tankPackage != undefined)
				me.tankPackage = new TankPackage(dataXML.tankPackage[0]);
			postProcess(dataXML);
		}

		//获得升级礼物
		public function fetchUpgradeGift(objectBalance:String):Boolean
		{
			InProcessWindow.getInstance().show("正在获取礼物");
			var me:PlayerInfo = PlayerInfoManager.getInstance().me;
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.FETCH_UPGRADE_GIFT;
			variables.level = me.level;
			variables.objectBalance = objectBalance;
			return postRequest(Profile.URL_Action, variables, handleFetchUpgradeGift);
		}
		
		private function handleFetchUpgradeGift(event:Event):void
		{
			InProcessWindow.getInstance().hide();
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var me:PlayerInfo = PlayerInfoManager.getInstance().me;
			me.currentLevel = me.level;
			if (dataXML.objPackage != undefined)
				me.objPackage = new ObjPackage(dataXML.objPackage[0]);
			if (dataXML.tankPackage != undefined)
				me.tankPackage = new TankPackage(dataXML.tankPackage[0]);
			postProcess(dataXML);
		}

		//获得礼物
		public function fetchGift(objectBalance:String):Boolean
		{
			InProcessWindow.getInstance().show("正在获取礼物");
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.FETCH_GIFT;
			variables.objectBalance = objectBalance;
			return postRequest(Profile.URL_Action, variables, handleFetchGift);
		}
		
		private function handleFetchGift(event:Event):void
		{
			InProcessWindow.getInstance().hide();
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			var player:PlayerInfo = PlayerInfoManager.getInstance().players[PlayerInfoManager.getInstance().myUserId];
			if (dataXML.objPackage != undefined)
				player.objPackage = new ObjPackage(dataXML.objPackage[0]);
			if (dataXML.tankPackage != undefined)
				player.tankPackage = new TankPackage(dataXML.tankPackage[0]);
			player.fetchGiftDate = dataXML.fetchGiftDate;
			postProcess(dataXML);
		}
		
		//保存系统信息
		public function saveSystemInfo():Boolean
		{
			var variables:URLVariables = new URLVariables();
			variables.action = ServerEvent.SAVE_SYSTEM_INFO;
			variables.effectVolume = int(BSound.getInstance().effectVolume * 1000);
			variables.musicVolume = int(BSound.getInstance().musicVolume * 1000);
			return postRequest(Profile.URL_Action, variables, handleSaveSystemInfo);
		}
		
		private function handleSaveSystemInfo(event:Event):void
		{
			var dataXML:XML = XML(event.target.data);
			preProcess(dataXML);
			postProcess(dataXML);
		}
		
		public static function redirectToGamePage():void
		{
			ExternalInterface.call("window.open", Profile.URL_GamePage, "_parent");
		}
		
		public static function sendFeed(ongoingMessage:String, messageIndex:int = -1):void
		{
			if (messageIndex < 0 || messageIndex > Config.basicConfig.feedMessages.length / 3)
			{
				messageIndex = Math.random() * int(Config.basicConfig.feedMessages.length / 3); 
			}
			var userMessage:String = Config.basicConfig.feedMessages[messageIndex * 3];
			var description:String = Config.basicConfig.feedMessages[messageIndex * 3 + 1];
			var imgUrl:String = Config.basicConfig.feedMessages[messageIndex * 3 + 2];
			ExternalInterface.call("tfShare", PlayerInfoManager.getInstance().myUserId, 0, ongoingMessage, userMessage, description, imgUrl);
		}
	}
}